package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-27
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void insertAmqpData(String contentStr) {
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        Object object = jsonObject.get("notify_data");

        //1.解析数据
        IotMsgNotifyData iotMsgNotifyData = BeanUtil.toBean(object, IotMsgNotifyData.class);
        //2.设备id 查询数据库
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(new QueryWrapper<Device>().eq("iot_id", deviceId));
        if(device == null){
            throw new RuntimeException("设备不存在");
        }
        //3.数据对象进行分析，获取properties map 数据循环插入到数据库
        iotMsgNotifyData.getBody().getServices().forEach(service -> {

            List<DeviceData> deviceDataList = new ArrayList<>();

            service.getProperties().forEach((key,value)->{

                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setIotId(deviceId);
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setFunctionId(key);
                deviceData.setDataValue(String.valueOf(value));
                //处理上报时间日期
                LocalDateTime eventTime =  LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
                //日期时区转换
                LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                deviceData.setAlarmTime(alarmTime);
                deviceData.setId(null);
                deviceDataList.add(deviceData);
            });
           this.saveBatch(deviceDataList);

           //把插入到数据库的数据，同时放入到redis 中
            redisTemplate.opsForHash().put("iot:device_data", deviceId, JSONUtil.toJsonStr(deviceDataList));
        });

    }
}
